package com.hucc.sqlitedemo;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.AbsListView;
import android.widget.ListView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 *  演示数据库分页
 *  select * from person limit 0,15; 当前页码第一条数据的下标，每页显示的数据条目
 *
 *  总条目 201
 *  每页条数 20
 *  总页数
 *  页码
 *
 *  1 页码为1时在listView中展示对应数据
 *  2 当listview加载完本页数据分页加载下一页数据
 */

public class PageActivity extends AppCompatActivity {

    private ListView  mListView;
    private SQLiteDatabase  db;
    private SQLiteHelper  mHelper;
    private int totalNum; //表示加载当前控件加载数据总条目
    private int pageSize = 15; // 表示当前数据条目
    private int pageNum; // 表示总页码
    private int currentPage = 1; // 当前页码
    private boolean isDivPage;
    private List<Person> totalList;

    private final String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/vote";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        mListView = (ListView)findViewById(R.id.list_view);

        mHelper = new SQLiteHelper(this);
        db = openDatabase(this);
        db = mHelper.getWritableDatabase();
        // db = SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READONLY);
        // 获取数据表数据总数目
        totalNum = DbManager.getDataCount(db,Constant.TABLE_NAME);
        // 根据总条目与每页展示数据条目，获得总页数
        pageNum = (int) Math.ceil(totalNum / pageSize);
        if (currentPage == 1){
             totalList = DbManager.getListByCurrentPage(db,Constant.TABLE_NAME,currentPage,pageSize);
        }

        final MyBaseAdapter mAdapter = new MyBaseAdapter(this, totalList);
        mListView.setAdapter(mAdapter);

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isDivPage && AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState){
                    if (currentPage<pageNum){
                        currentPage++;
                        // 根据最新页码加载获取集合存储到数据源中
                        totalList.addAll(DbManager.getListByCurrentPage(db,Constant.TABLE_NAME, currentPage,pageSize));
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                isDivPage = ((firstVisibleItem + visibleItemCount)==totalItemCount);

            }
        });
    }

    private SQLiteDatabase openDatabase(Context context) {
        File file = new File(DATABASE_PATH);
        //查看数据库文件是否存在
        if (file.exists()){
            Log.i("test", "存在数据库");
            // 存在则直接返回打开的数据库
            return SQLiteDatabase.openOrCreateDatabase(file, null);
        }else{
            //不存在先创建文件夹
            File path = new File(DATABASE_PATH);
            Log.i("test", "pathStr="+path);
            if (path.mkdir()){
                Log.i("test", "创建成功");
            }else{
                Log.i("test", "创建失败");
            }
            try {
                //得到资源
                AssetManager am = context.getAssets();
                //得到数据库的输入流
                // InputStream is = am.open(Constant.DATABASE_NAME);
                // InputStream is = am.open("info.db");
                InputStream is = am.open(String.valueOf(R.raw.info));
                Log.i("test", is+"");
                //用输出流写到SDcard上面
                FileOutputStream fos = new FileOutputStream(file);
                Log.i("test", "fos="+fos);
                Log.i("test", "file="+file);
                //创建byte数组  用于1KB写一次
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = is.read(buffer))>0){
                    Log.i("test", "得到");
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            }catch (IOException e){
                e.printStackTrace();
                return null;
            }
        }
        return openDatabase(context);
    }
}
